"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Progress } from "@/components/ui/progress"
import {
  ArrowLeft,
  FileText,
  Download,
  Eye,
  Lightbulb,
  Target,
  Users,
  DollarSign,
  TrendingUp,
  Shield,
} from "lucide-react"

export default function BusinessPlanGeneratorPage() {
  const router = useRouter()
  const [currentStep, setCurrentStep] = useState(1)
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [formData, setFormData] = useState({
    companyName: "",
    industry: "",
    businessModel: "",
    targetMarket: "",
    problemStatement: "",
    solution: "",
    uniqueValue: "",
    marketSize: "",
    competitors: "",
    revenueModel: "",
    fundingNeeded: "",
    teamSize: "",
    timeline: "",
  })

  const totalSteps = 6
  const progress = (currentStep / totalSteps) * 100

  const industries = [
    "互联网/科技",
    "电子商务",
    "教育培训",
    "医疗健康",
    "金融服务",
    "餐饮服务",
    "制造业",
    "房地产",
    "文化娱乐",
    "其他",
  ]

  const businessModels = [
    "B2B (企业对企业)",
    "B2C (企业对消费者)",
    "C2C (消费者对消费者)",
    "B2B2C (企业对企业对消费者)",
    "平台模式",
    "订阅模式",
    "免费增值模式",
    "其他",
  ]

  const handleInputChange = (field, value) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }))
  }

  const handleNext = () => {
    if (currentStep < totalSteps) {
      setCurrentStep(currentStep + 1)
    }
  }

  const handlePrevious = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1)
    }
  }

  const handleGenerate = () => {
    // 模拟生成商业计划书
    alert("商业计划书生成成功！正在为您准备下载...")
    console.log("生成的数据:", formData)
  }

  // 检查用户登录状态
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    setCurrentUser(JSON.parse(user))
    setIsLoading(false)
  }, [router])

  const renderStepContent = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <Target className="w-12 h-12 text-blue-600 mx-auto mb-4" />
              <h2 className="text-2xl font-bold text-slate-900 mb-2">基本信息</h2>
              <p className="text-slate-600">让我们从基础信息开始了解您的项目</p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">公司/项目名称</label>
                <Input
                  placeholder="请输入您的公司或项目名称"
                  value={formData.companyName}
                  onChange={(e) => handleInputChange("companyName", e.target.value)}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">所属行业</label>
                <Select value={formData.industry} onValueChange={(value) => handleInputChange("industry", value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择您的行业" />
                  </SelectTrigger>
                  <SelectContent>
                    {industries.map((industry) => (
                      <SelectItem key={industry} value={industry}>
                        {industry}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">商业模式</label>
                <Select
                  value={formData.businessModel}
                  onValueChange={(value) => handleInputChange("businessModel", value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择您的商业模式" />
                  </SelectTrigger>
                  <SelectContent>
                    {businessModels.map((model) => (
                      <SelectItem key={model} value={model}>
                        {model}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">目标市场</label>
                <Textarea
                  placeholder="描述您的目标客户群体和市场定位"
                  value={formData.targetMarket}
                  onChange={(e) => handleInputChange("targetMarket", e.target.value)}
                  className="min-h-[100px]"
                />
              </div>
            </div>
          </div>
        )

      case 2:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <Lightbulb className="w-12 h-12 text-yellow-600 mx-auto mb-4" />
              <h2 className="text-2xl font-bold text-slate-900 mb-2">问题与解决方案</h2>
              <p className="text-slate-600">清晰地定义您要解决的问题和提供的解决方案</p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">问题陈述</label>
                <Textarea
                  placeholder="描述您要解决的核心问题，这个问题有多严重？影响了多少人？"
                  value={formData.problemStatement}
                  onChange={(e) => handleInputChange("problemStatement", e.target.value)}
                  className="min-h-[120px]"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">解决方案</label>
                <Textarea
                  placeholder="详细描述您的产品或服务如何解决上述问题"
                  value={formData.solution}
                  onChange={(e) => handleInputChange("solution", e.target.value)}
                  className="min-h-[120px]"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">独特价值主张</label>
                <Textarea
                  placeholder="您的产品/服务与竞争对手相比有什么独特优势？"
                  value={formData.uniqueValue}
                  onChange={(e) => handleInputChange("uniqueValue", e.target.value)}
                  className="min-h-[100px]"
                />
              </div>
            </div>
          </div>
        )

      case 3:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <TrendingUp className="w-12 h-12 text-green-600 mx-auto mb-4" />
              <h2 className="text-2xl font-bold text-slate-900 mb-2">市场分析</h2>
              <p className="text-slate-600">分析您的目标市场规模和竞争环境</p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">市场规模</label>
                <Textarea
                  placeholder="描述您的目标市场规模，包括TAM（总体市场）、SAM（可服务市场）、SOM（可获得市场）"
                  value={formData.marketSize}
                  onChange={(e) => handleInputChange("marketSize", e.target.value)}
                  className="min-h-[120px]"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">竞争分析</label>
                <Textarea
                  placeholder="列出主要竞争对手，分析他们的优势和劣势，以及您的差异化策略"
                  value={formData.competitors}
                  onChange={(e) => handleInputChange("competitors", e.target.value)}
                  className="min-h-[120px]"
                />
              </div>
            </div>
          </div>
        )

      case 4:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <DollarSign className="w-12 h-12 text-blue-600 mx-auto mb-4" />
              <h2 className="text-2xl font-bold text-slate-900 mb-2">商业模式与收入</h2>
              <p className="text-slate-600">详细说明您的盈利模式和收入来源</p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">收入模式</label>
                <Textarea
                  placeholder="描述您的收入来源：一次性付费、订阅、佣金、广告等"
                  value={formData.revenueModel}
                  onChange={(e) => handleInputChange("revenueModel", e.target.value)}
                  className="min-h-[120px]"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">融资需求</label>
                <Input
                  placeholder="您需要多少资金？（万元）"
                  value={formData.fundingNeeded}
                  onChange={(e) => handleInputChange("fundingNeeded", e.target.value)}
                />
              </div>
            </div>
          </div>
        )

      case 5:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <Users className="w-12 h-12 text-purple-600 mx-auto mb-4" />
              <h2 className="text-2xl font-bold text-slate-900 mb-2">团队与执行</h2>
              <p className="text-slate-600">介绍您的团队和执行计划</p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">团队规模</label>
                <Input
                  placeholder="当前团队人数"
                  value={formData.teamSize}
                  onChange={(e) => handleInputChange("teamSize", e.target.value)}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">发展时间线</label>
                <Textarea
                  placeholder="描述您的产品开发和市场推广时间线，包括重要里程碑"
                  value={formData.timeline}
                  onChange={(e) => handleInputChange("timeline", e.target.value)}
                  className="min-h-[120px]"
                />
              </div>
            </div>
          </div>
        )

      case 6:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <Shield className="w-12 h-12 text-green-600 mx-auto mb-4" />
              <h2 className="text-2xl font-bold text-slate-900 mb-2">确认信息</h2>
              <p className="text-slate-600">请确认您填写的信息，我们将为您生成专业的商业计划书</p>
            </div>

            <div className="space-y-4">
              <Card>
                <CardContent className="p-4">
                  <h3 className="font-semibold mb-2">项目概览</h3>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-slate-500">项目名称：</span>
                      <span className="font-medium">{formData.companyName || "未填写"}</span>
                    </div>
                    <div>
                      <span className="text-slate-500">所属行业：</span>
                      <span className="font-medium">{formData.industry || "未选择"}</span>
                    </div>
                    <div>
                      <span className="text-slate-500">商业模式：</span>
                      <span className="font-medium">{formData.businessModel || "未选择"}</span>
                    </div>
                    <div>
                      <span className="text-slate-500">融资需求：</span>
                      <span className="font-medium">
                        {formData.fundingNeeded ? `${formData.fundingNeeded}万元` : "未填写"}
                      </span>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <div className="bg-blue-50 p-4 rounded-lg">
                <h4 className="font-medium text-blue-900 mb-2">生成的商业计划书将包含：</h4>
                <ul className="text-sm text-blue-800 space-y-1">
                  <li>• 执行摘要</li>
                  <li>• 公司描述</li>
                  <li>• 市场分析</li>
                  <li>• 产品/服务介绍</li>
                  <li>• 营销策略</li>
                  <li>• 财务预测</li>
                  <li>• 风险分析</li>
                  <li>• 附录资料</li>
                </ul>
              </div>
            </div>
          </div>
        )

      default:
        return null
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">验证登录状态...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30">
      {/* 顶部导航 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/50 sticky top-0 z-50">
        <div className="max-w-4xl mx-auto px-6 py-4">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" onClick={() => router.back()}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回
            </Button>
            <div className="flex items-center space-x-2">
              <FileText className="w-6 h-6 text-blue-600" />
              <h1 className="text-xl font-semibold text-slate-900">商业计划书生成器</h1>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-4xl mx-auto px-6 py-8">
        {/* 进度条 */}
        <div className="mb-8">
          <div className="flex justify-between items-center mb-2">
            <span className="text-sm font-medium text-slate-700">
              步骤 {currentStep} / {totalSteps}
            </span>
            <span className="text-sm text-slate-500">{Math.round(progress)}% 完成</span>
          </div>
          <Progress value={progress} className="h-2" />
        </div>

        {/* 主要内容 */}
        <Card className="mb-8">
          <CardContent className="p-8">{renderStepContent()}</CardContent>
        </Card>

        {/* 操作按钮 */}
        <div className="flex justify-between">
          <Button variant="outline" onClick={handlePrevious} disabled={currentStep === 1}>
            上一步
          </Button>

          <div className="flex space-x-3">
            {currentStep < totalSteps ? (
              <Button onClick={handleNext}>下一步</Button>
            ) : (
              <div className="flex space-x-3">
                <Button variant="outline" onClick={handleGenerate}>
                  <Eye className="w-4 h-4 mr-2" />
                  预览
                </Button>
                <Button onClick={handleGenerate}>
                  <Download className="w-4 h-4 mr-2" />
                  生成并下载
                </Button>
              </div>
            )}
          </div>
        </div>

        {/* 帮助提示 */}
        <Card className="mt-8 bg-blue-50 border-blue-200">
          <CardContent className="p-6">
            <div className="flex items-start space-x-3">
              <Lightbulb className="w-5 h-5 text-blue-600 mt-0.5" />
              <div>
                <h3 className="font-medium text-blue-900 mb-1">小贴士</h3>
                <p className="text-sm text-blue-800">
                  {currentStep === 1 && "清晰的项目定位是成功的第一步，请尽量具体地描述您的项目。"}
                  {currentStep === 2 && "问题描述越具体，解决方案就越有说服力。建议用数据支撑您的观点。"}
                  {currentStep === 3 && "市场分析要基于真实数据，可以引用行业报告或调研结果。"}
                  {currentStep === 4 && "收入模式要切实可行，建议提供多种收入来源以降低风险。"}
                  {currentStep === 5 && "团队是投资人最关注的因素之一，突出团队的专业能力和执行力。"}
                  {currentStep === 6 && "生成后的商业计划书可以进一步编辑和完善，建议根据具体场景调整内容。"}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </main>
    </div>
  )
}
